<?php
namespace app\api\controller;

use \think\Controller;
use \think\Db;
class Order extends Base
{
    /**
     * 获取包的ANR/IOS价格、会员的ANR/IOS价格以及各会员等级权限说明
     */
    public function getConfigs()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //1、包的价格
        $bag = array();
        $bagData = Db::table('up_top_bag')->column('t_b_price');
        $bag['android'] = array('top'=>$bagData[0],'fresh'=>$bagData[1]);
        $bag['ios'] = array('top'=>$bagData[2],'fresh'=>$bagData[3]);
        //2、会员价格
        $member = array();
        $memberData = Db::table('up_member_price')->column('mp_price');
        $memberData2 = Db::table('up_member_price')->column('mp_big_money');
        $member['android'] = array('three'=>$memberData[0],'six'=>$memberData[1],'year'=>$memberData[2]);
        $member['android_old'] = array('three'=>$memberData2[0],'six'=>$memberData2[1],'year'=>$memberData2[2]);
        $member['ios'] = array('three'=>$memberData[3],'six'=>$memberData[4],'year'=>$memberData[5]);
        $member['ios_old'] = array('three'=>$memberData2[3],'six'=>$memberData2[4],'year'=>$memberData2[5]);
        //3、会员权限说明次数
        $config = Db::table('up_member_config')->where('mc_auth','>',1)->select();
        //4、我当前的会员等级
        $now_auth_info = $this->getMemberConfig($user_id);
        return json(['status'=>200,'bag_price'=>$bag,'member_price'=>$member,'auth_info'=>$config,'now_auth_info'=>$now_auth_info]);
    }

    /**
     * 确认订单页——支付
     * 哪一类型：which（1是会员购买 2是置顶包 3是刷新包）（bag对应表的id）
     * 如果是会员：authtype（买的是何种会员(2季度  3半年  4一年）
     * 哪方支付：type（1是支付宝  2是微信）
     */
    public function makeOrder(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $number = date('YmdHis') . rand(1000000,9999999);
        $today = date('Y-m-d');
        $order = array();
        $order['order_number'] = $number;
        $order['order_user_id'] = $user_id;
        $order['order_type'] = $which;
        $order['order_date'] = $today;
        $order['order_time'] = date('Y-m-d H:i:s');
        //1、买的是会员还是包
        if($which == 1){
            $money = Db::table('up_member_price')
                ->where('mp_auth',$authtype)
                ->where('mp_phone',1)
                ->value('mp_price');
            $order['order_money'] = $money;
            $order['order_auth_type'] = $authtype;
            //1-1：如果是会员算一下会员日期
            $user = Db::table('up_u_user')
                ->where('user_id', $user_id)
                ->field('user_auth,user_auth_start,user_auth_end')
                ->find();
            if($authtype == 2){$many = 3;}
            if($authtype == 3){$many = 6;}
            if($authtype == 4){$many = 12;}
            if($user['user_auth'] > 1){ //往后延
                $order['order_auth_begin'] = $user['user_auth_start'];
                $order['order_auth_end'] = $this->getNextMonthDays($user['user_auth_end'],$many+1);
            }else{//新买的和升级的都是从今天开始
                $order['order_auth_begin'] = $today;
                $order['order_auth_end'] = date("Y-m-d",strtotime("+$many month"));
            }
        }else{
            $money = Db::table('up_top_bag')
                ->where('t_b_id',$which-1)
                ->value('t_b_price');
            $order['order_money'] = $money;
        }
        Db::startTrans();
        try{
            Db::table('up_order')->insert($order);

            Db::commit();
            if($type == 1){
                $respont = $this->getParam($number,$money);
                return json_encode($respont);
            }else{
                $orderWx = array();
                $orderWx['body'] = '会员购买';
                $orderWx['total_fee'] = $money*100;
                $orderWx['out_trade_no'] = $number;
                $orderWx['product_id'] = '';
                $orderWx['trade_type'] = 'APP';
                $respont = $this->WeChatPayReady($orderWx);
                return json_encode(['status'=>200,'msgsss'=>$respont]);
            }
        }catch (\Exception $e) {
            Db::rollback();
            return json_encode(['status'=>0,'msgsss'=>'生成订单失败，请联系管理员']);
        }
    }


    /**
     * 支付回调
     * @return string
     */
    public function huidiao()
    {
        $getInfo = $this->checkReturn();
        if($getInfo){
            if($getInfo['trade_status'] == 'TRADE_SUCCESS' || $getInfo['trade_status'] == 'TRADE_FINISHED'){
                $number = $getInfo['out_trade_no'];
                $transaction_id = $getInfo['trade_no'];
                $paytime = $getInfo['gmt_payment'];
                if($this->doneOrder($number,$transaction_id,$paytime)){
                    die('success');
                }else{
                    return 'error';
                }
            }
        }
    }
    public function huidiaoWx()
    {
        $xml=file_get_contents('php://input', 'r');
        $getInfo=$this->toArray($xml);
        $data_sign=$getInfo['sign'];
        unset($getInfo['sign']);
        $sign = $this->makeSign($getInfo);
        // 判断签名是否正确  判断支付状态
        if ($sign === $data_sign && $getInfo['return_code'] == 'SUCCESS' && $getInfo['result_code'] == 'SUCCESS') {
            $number = $getInfo['out_trade_no'];
            $transaction_id = $getInfo['transaction_id'];
            $paytime = $this->getDateBytimeDate("{$getInfo['time_end']}");
            if ($this->doneOrder($number, $transaction_id, $paytime)) {
                //通知和推送
                $result = $getInfo;
            } else {
                $result = false;
            }
        }else{
            $result = false;
        }
        // 返回状态给微信服务器----------------
        if ($result) {
            $str='<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
        }else{
            $str='<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[签名失败]]></return_msg></xml>';
        }
        echo $str;
        exit();
        return $result;
    }
    public function doneOrder($number,$transaction_id,$paytime)
    {
        Db::startTrans();
        try{
            $order = Db::table('up_order')->where('order_number', $number)->find();
            //1、支付成功改状态
            $update = array();
            $update['order_status'] = 2;
            $update['order_back_transaction_id'] = $transaction_id;
            $update['order_paytime'] = $paytime;
            Db::table('up_order')
                ->where('order_number', $number)
                ->update($update);
            //1-2、改会员时长或包数量
            $type = $order['order_type'];//1是会员购买 2是置顶包 3是刷新包
            if($type == 1){
                $update2 = array();
                $update2['user_auth'] = $order['order_auth_type'];
                $update2['user_auth_start'] = $order['order_auth_begin'];
                $update2['user_auth_end'] = $order['order_auth_end'];
                Db::table('up_u_user')
                    ->where('user_id',$order['order_user_id'])
                    ->update($update2);
            }elseif ($type == 2){
                Db::table('up_u_user')
                    ->where('user_id',$order['order_user_id'])
                    ->setInc('user_mytop');
            }elseif ($type == 3){
                Db::table('up_u_user')
                    ->where('user_id',$order['order_user_id'])
                    ->setInc('user_myfresh');
            }else{
                Db::rollback();
                return false;
            }
            Db::commit();
            return true;
        }catch (\Exception $e) {
            Db::rollback();
            return false;
        }

    }



}